package forum.filter;

import forum.Variable;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Ivan
 * Date: 2010-7-8
 * Time: 16:41:55
 */

public class Loginfilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        String url = ((HttpServletRequest) req).getRequestURI();

        String sessionUsername = (String) ((HttpServletRequest) req).getSession().getAttribute("username");

        if (!url.endsWith("login.jsp") && sessionUsername == null) {
            String path = ((HttpServletRequest) req).getContextPath();
            String basePase =  req.getScheme() + "://" +  req.getServerName() + ":" +  req.getServerPort() + path + "/forum/login.jsp";
            
            String history = ((HttpServletRequest) req).getRequestURI();
            history = history.substring(history.lastIndexOf("/")+1);
            ((HttpServletRequest) req).getSession().setAttribute("history_url", history);
            ((HttpServletResponse) resp).sendRedirect(basePase);
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
